package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * UV指标计算（日活人数）
 * @author Archie
 * @date 2021-10-20 8:39
 * @description
 */
public class DwmUvApp extends BaseAppV1 {

	public static void main(String[] args) {
		new DwmUvApp().init(3001, 1, "DwmUvApp", "DwmUvApp", Constant.TOPIC_DWD_PAGE);
	}

	@Override
	protected void run(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
		stream
				.map(JSON::parseObject)
				.assignTimestampsAndWatermarks(
						WatermarkStrategy
								.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
								.withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
				)
				.keyBy(obj -> obj.getJSONObject("common").getString("uid"))
				.window(TumblingEventTimeWindows.of(Time.seconds(5)))
				.process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {

					private ValueState<Long> firstVisitState;
					private SimpleDateFormat sdf;

					@Override
					public void open(Configuration parameters) throws Exception {
						firstVisitState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("firstVisitState", Long.class));
						sdf = new SimpleDateFormat("yyyy-MM-dd");
					}

					@Override
					public void process(String s, Context context, Iterable<JSONObject> elements, Collector<JSONObject> out) throws Exception {
						// 1. 处理跨天逻辑
						// 今天
						String today = sdf.format(context.window().getStart());
						// 昨天
						long yesterdayMs = firstVisitState.value() == null ? 0L : firstVisitState.value();
						String yesterday = sdf.format(yesterdayMs);
						if(!today.equals(yesterday)){
							firstVisitState.clear();
						}

						// 2. 从当前uid 的 第一个窗口 找到最早的数据
						if (firstVisitState.value() == null) {
							List<JSONObject> list = AtguiguUtil.toList(elements);
							JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
							out.collect(min);
							firstVisitState.update(min.getLong("ts"));
						}
					}
				})
				.map(JSONAware::toJSONString)
				.addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));
	}
}
